<template>
  <div class="menus-manage">
    <!-- 面包屑 -->
    <div class="bread-crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/home/hours'}">员工工时</el-breadcrumb-item>
        <el-breadcrumb-item>个人工时</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="main-middle">
      <el-card class="box-card">
        <!-- 查询条件 -->
        <el-row class="table-selbox" v-if="btnSel">
          <!-- 查询条件表单 -->
          <el-form :inline="true" :model="formInline" >
            <!-- 项目名称 -->
            <el-form-item label="项目名称">
              <el-select filterable auto-complete="off" placeholder="请选择">
                <el-option label="无" value></el-option>
                <!-- 循环所有项目 项目名称 项目ID -->
              </el-select>
            </el-form-item>
            <el-form-item label="月份">
              <el-date-picker type="month" placeholder="选择月"></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search">搜索</el-button>
            </el-form-item>
          </el-form>
        </el-row>
        <!-- 基本操作按钮 是否授权显示-->
        <el-row class="table-btns" v-if="[btnAdd,btnDel,btnUpload,btnDown].indexOf(true) > -1">
          <el-button
            v-if="btnAdd"
            icon="el-icon-document-add"
            type="success"
            style="font-weight: 400;"
            @click="addHandle"
          >添加</el-button>
          <!-- 个人工时列表暂无上传下载操作
          <el-button type="primary" size="medium" style="float:right;" v-if="btnUpload">
            <i class="fa fa-cloud-upload" aria-hidden="true"></i> 上传
          </el-button>
          <el-button type="success" size="medium" style="float:right;" v-if="btnDown">
            <i class="fa fa-cloud-download" aria-hidden="true"></i> 下载
          </el-button>
          -->
        </el-row>
        <!-- 数据列表 -->
        <el-table
          :data="menusData"
          @selection-change="selsChange"
          show-summary
          :summary-method="getSummaries"
          border
          style="width: 100%"
          height="395"
          ref="menusData"
        >
          <!-- 项目名称 -->
          <el-table-column
            :show-overflow-tooltip="true"
            prop="proName"
            label="项目名称"
            width="200"
            align="center"
            fixed
          ></el-table-column>
          <!-- 1号 -->
          <el-table-column sortable label="1号" width="100"></el-table-column>
          <!-- 2号 -->
          <el-table-column sortable label="2号" width="100"></el-table-column>
          <!-- 3号 -->
          <el-table-column sortable label="3号" width="100"></el-table-column>
          <!-- 4号 -->
          <el-table-column sortable label="4号" width="100"></el-table-column>
          <!-- 5号 -->
          <el-table-column sortable label="5号" width="100"></el-table-column>
          <!-- 6号 -->
          <el-table-column sortable label="6号" width="100"></el-table-column>
          <!-- 7号 -->
          <el-table-column sortable label="7号" width="100"></el-table-column>
          <!-- 8号 -->
          <el-table-column sortable label="8号" width="100"></el-table-column>
          <!-- 9号 -->
          <el-table-column sortable label="9号" width="100"></el-table-column>
          <!-- 10号 -->
          <el-table-column sortable label="10号" width="100"></el-table-column>

          <!-- 11号 -->
          <el-table-column sortable label="11号" width="100"></el-table-column>
          <!-- 12号 -->
          <el-table-column sortable label="12号" width="100"></el-table-column>
          <!-- 13号 -->
          <el-table-column sortable label="13号" width="100"></el-table-column>
          <!-- 14号 -->
          <el-table-column sortable label="14号" width="100"></el-table-column>
          <!-- 15号 -->
          <el-table-column sortable label="15号" width="100"></el-table-column>
          <!-- 16号 -->
          <el-table-column sortable label="16号" width="100"></el-table-column>
          <!-- 17号 -->
          <el-table-column sortable label="17号" width="100"></el-table-column>
          <!-- 18号 -->
          <el-table-column sortable label="18号" width="100"></el-table-column>
          <!-- 19号 -->
          <el-table-column sortable label="19号" width="100"></el-table-column>
          <!-- 20号 -->
          <el-table-column sortable label="20号" width="100"></el-table-column>

          <!-- 21号 -->
          <el-table-column sortable label="21号" width="100"></el-table-column>
          <!-- 22号 -->
          <el-table-column sortable label="22号" width="100"></el-table-column>
          <!-- 23号 -->
          <el-table-column sortable label="23号" width="100"></el-table-column>
          <!-- 24号 -->
          <el-table-column sortable label="24号" width="100"></el-table-column>
          <!-- 25号 -->
          <el-table-column sortable label="25号" width="100"></el-table-column>
          <!-- 26号 -->
          <el-table-column sortable label="26号" width="100"></el-table-column>
          <!-- 27号 -->
          <el-table-column sortable label="27号" width="100"></el-table-column>
          <!-- 28号 -->
          <el-table-column sortable label="28号" width="100"></el-table-column>
          <!-- 29号 -->
          <el-table-column sortable label="29号" width="100"></el-table-column>
          <!-- 30号 -->
          <el-table-column sortable label="30号" width="100"></el-table-column>
          <!-- 31号 -->
          <el-table-column sortable label="31号" width="100"></el-table-column>

          <!-- 合计 -->
          <el-table-column sortable label="合计" fixed="right" align="center" width="160"></el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="table-pageblock">
          <!-- current-page 当前页数  page-size 每页显示数 total 总页数-->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[20,50,80,100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </el-card>

      <!-- 弹窗 新增 -->
      <el-dialog
        :title="textMap[dialogStatus]"
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false"
      >
        <!-- 添加 修改弹窗表单 -->
        <el-form ref="editForm" :model="editForm" label-width="80px" :rules="editFormRules">
          <!-- 项目名称 -->
          <el-form-item label="项目名称">
            <el-select filterable auto-complete="off" placeholder="请选择" style="width:100%;">
              <el-option label="无" value></el-option>
              <!-- 循环所有项目 项目名称 项目ID -->
            </el-select>
          </el-form-item>
          <!-- 日期 -->
          <el-form-item label="选择日期">
            <el-date-picker
              type="date"
              v-model="editForm.day"
              @change="getDay"
              placeholder="选择日期"
              style="width:100%;"
            ></el-date-picker>
          </el-form-item>
          <el-form-item style="height:400px;">
            <ul class="dcal-weeks">
              <li v-for="(item, index) in weeks" :key="index">
                <template v-if="index === 0">
                  <!-- Monday -->
                  <span>星期一</span>
                  <span>{{item}}</span>
                </template>
                <template v-if="index === 1">
                  <!-- Tuesday -->
                  <span>星期二</span>
                  <span>{{item}}</span>
                </template>
                <template v-if="index === 2">
                  <!-- Wednesday -->
                  <span>星期三</span>
                  <span>{{item}}</span>
                </template>
                <template v-if="index === 3">
                  <!-- Thursday -->
                  <span>星期四</span>
                  <span>{{item}}</span>
                </template>
                <template v-if="index === 4">
                  <!-- Friday -->
                  <span>星期五</span>
                  <span>{{item}}</span>
                </template>
                <template v-if="index === 5">
                  <!-- Saturday -->
                  <span>星期六</span>
                  <span>{{item}}</span>
                </template>
                <template v-if="index === 6">
                  <!-- Sunday -->
                  <span>星期天</span>
                  <span>{{item}}</span>
                </template>
              </li>
            </ul>
            <ul class="dcal-hours">
              <li v-for="(day, index) in hours" :key="index">
                <el-input-number :min="day.hour" :max="day.total" :placeholder="day.placeholder"></el-input-number>
              </li>
            </ul>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <!-- 取消 关闭弹窗 -->
          <el-button @click.native="dialogFormVisible=false">取消</el-button>
          <!-- 添加 初始化弹窗表单数据 -->
          <el-button
            v-if="dialogStatus=='create'"
            type="primary"
            @click="createData"
            :disabled="isSubmit"
          >添加</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// 引入时间格式化插件
import moment from 'moment';

export default {
  // 父组件传值子组件
  props: {
    // 按钮级权限
    btns: {
      type: Object
    }
  },

  // 无白屏刷新方法注入
  inject: ['reload'],

  // 监听
  watch: {
    // 按钮权限数据
    btns (val, oldVal) {
      // 刷新当前页
      this.reload();
    }
  },

  // 过滤器
  filters: {
    // 时间显示过滤
    filterTime (value) {
      return moment(value).format('YYYY-MM-DD HH:mm:ss');
    }
  },
  // 当前实例数据
  data () {
    return {
      // 按钮显示隐藏  - 默认值
      btnSel: true,
      btnDel: true,
      btnUpload: true,
      btnDown: true,
      btnAdd: true,
      btnEdit: true,

      // 搜索条件
      formInline: {
        proName: ''
      },

      // 列表数据
      menusData: [{}],
      // 当前页
      currentPage: 1,
      // 当前数
      pageSize: 20,
      // 总条目数
      total: 20,

      // 弹窗类别
      dialogStatus: '',
      // 弹窗标题
      textMap: {
        edit: '修改信息',
        create: '添加信息'
      },

      // 弹窗是否显示
      dialogFormVisible: false,

      // 编辑界面输入框校验规则
      editFormRules: {},

      // 界面默认数据
      editForm: {},

      weeks: [],
      hours: []
    };
  },
  // 创建实例后执行
  created () {
    // 按钮级授权
    this.authorization(this.$store.state.btns);
  },
  methods: {
    getSummaries (param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '剩余工时';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += ' 元';
        } else {
          sums[index] = 'N/A';
        }
      });

      return sums;
    },

    // 查询
    selHandle: function () {
      // 收集请求数据
      let params = {
        year: '',
        month: '',
        pageNum: this.currentPage,
        pageSize: this.pageSize
      };
      // Fri Mar 01 2019 00:00:00 GMT+0800
      let dateMonth = this.formInline.month;
      params.year = dateMonth.getFullYear();
      params.month = dateMonth.getMonth() + 1;

      // 根据年月查询分页数据
      this.$http
        .raw('api/findColHisByMonthAndYear', params)
        .then(res => {
          let { code, datas } = res;
          // 判断Code状态
          if (code === 0) {
            // 总页数
            this.total = datas.total;
            // 数据结果集
            this.menusData = datas.list;
            // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
            if (!datas.list.length && this.currentPage !== 1) {
              // 当前页减一
              this.currentPage -= 1;
              // 调用自己
              this.getmenusDataByPage();
            }
          }
        })
        .catch(err => {
          if (err === undefined) {
            this.$message({
              message: '服务器响应异常！',
              type: 'error'
            });
            return false;
          }
        });
    },

    // 刷新页面数据
    getmenusDataByPage () {
      // 收集请求参数
      let params = {
        year: '',
        month: '',
        pageNum: this.currentPage,
        pageSize: this.pageSize
      };

      // 获取分页数据
      this.$http
        .raw('api/findColHisByMonthAndYear', params)
        .then(res => {
          let { code, datas } = res;
          if (code === 0) {
            // 总页数
            this.total = datas.total;
            // 数据结果集
            this.menusData = datas.list;
            // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
            if (!datas.list.length && this.currentPage !== 1) {
              // 当前页减一
              this.currentPage -= 1;
              // 调用自己
              this.getmenusDataByPage();
            }
          }
        })
        .catch(err => {
          if (err === undefined) {
            this.$message({
              message: '服务器响应异常！',
              type: 'error'
            });
            return false;
          }
        });
    },

    // 每页显示的条数改变
    handleSizeChange (val) {
      this.pageSize = val;
      // 调用刷新页面
      this.getmenusDataByPage();
    },
    // 当前页码
    handleCurrentChange (val) {
      this.currentPage = val;
      // 调用
      this.getmenusDataByPage();
    },
    // 下个月
    // this.$EventCalendar.nextMonth()

    // 上个月
    // this.$EventCalendar.preMonth()

    // //到指定日期
    // this.$EventCalendar.toDate('2016/11/12')

    getDay () {
      let day = moment(new Date(this.editForm.day).getTime()).format(
        'YYYY-MM-DD'
      );
      let monday = moment(day)
        .weekday(1)
        .format('YYYY/MM/DD');
      let tuesday = moment(day)
        .weekday(2)
        .format('YYYY/MM/DD');
      let wednesday = moment(day)
        .weekday(3)
        .format('YYYY/MM/DD');
      let thursday = moment(day)
        .weekday(4)
        .format('YYYY/MM/DD');
      let friday = moment(day)
        .weekday(5)
        .format('YYYY/MM/DD');
      let saturday = moment(day)
        .weekday(6)
        .format('YYYY/MM/DD');
      let sunday = moment(day)
        .weekday(7)
        .format('YYYY/MM/DD');

      this.weeks = [
        monday,
        tuesday,
        wednesday,
        thursday,
        friday,
        saturday,
        sunday
      ];

      this.hours = [
        {
          day: monday,
          hour: 0,
          total: 10,
          placeholder: '剩余：10'
        },
        {
          day: tuesday,
          hour: 0,
          total: 10,
          placeholder: '剩余：10'
        },
        {
          day: wednesday,
          hour: 0,
          total: 10,
          placeholder: '剩余：10'
        },
        {
          day: thursday,
          hour: 0,
          total: 10,
          placeholder: '剩余：10'
        },
        {
          day: friday,
          hour: 0,
          total: 10,
          placeholder: '剩余：10'
        },
        {
          day: saturday,
          hour: 0,
          total: 10,
          placeholder: '剩余：10'
        },
        {
          day: sunday,
          hour: 0,
          total: 10,
          placeholder: '剩余：10'
        }
      ];
    },

    // 刷新本月所有记录
    reset () {
      this.reload();
    },

    // 显示新增界面
    addHandle: function () {
      // 弹窗类型
      this.dialogStatus = 'create';
      // 弹窗显示状态
      this.dialogFormVisible = true;
      // 重置新增界面默认数据
      this.editForm = {};
    },

    // 添加
    createData: function () {
      // 防止重复提交
      this.isSubmit = true;
      setTimeout(() => {
        this.isSubmit = false;
      }, 1000);

      this.$nextTick(() => {
        // 判断是否通过验证规则验证
        this.$refs['editForm'].validate(valid => {
          if (valid) {
            // 获取菜单名称
            let menuName = {
              menuName:
                this.editForm.menuName === null ? '' : this.editForm.menuName
            };
            // 根据菜单名称判断是否被占用
            this.$http
              .post('api/getMenuCount', menuName)
              .then(res => {
                let { code, datas } = res;
                // 判断Code状态
                if (code === 0) {
                  // 判断是否被占用
                  if (datas > 0) {
                    this.$message({
                      message: '菜单名称被占用',
                      type: 'error'
                    });
                  } else {
                    // 收集请求参数
                    let params = {
                      parentId:
                        this.editForm.parentId === null
                          ? ''
                          : this.editForm.parentId,
                      menuName:
                        this.editForm.menuName === null
                          ? ''
                          : this.editForm.menuName,
                      icon:
                        this.editForm.icon === null ? '' : this.editForm.icon,
                      router:
                        this.editForm.router === null
                          ? ''
                          : this.editForm.router,
                      sort:
                        this.editForm.sort === null ? '' : this.editForm.sort,
                      note:
                        this.editForm.note === null ? '' : this.editForm.note
                    };
                    // 添加菜单信息
                    this.$http
                      .raw('api/insertMenu', params)
                      .then(res => {
                        let { code } = res;
                        // 判断Code状态
                        if (code === 0) {
                          this.$message({
                            message: '添加成功！',
                            type: 'success'
                          });
                          // 重新初始化弹窗表单数据
                          this.$refs['editForm'].resetFields();
                          // 关闭弹窗
                          this.dialogFormVisible = false;
                          // 刷新列表
                          this.getmenusDataByPage();
                        }
                      })
                      .catch(err => {
                        if (err === undefined) {
                          this.$message({
                            message: '服务器响应异常！',
                            type: 'error'
                          });
                          return false;
                        }
                      });
                  }
                }
              })
              .catch(err => {
                if (err === undefined) {
                  this.$message({
                    message: '服务器响应异常！',
                    type: 'error'
                  });
                  return false;
                }
              });
          }
        });
      });
    },

    // 切换月份
    handleMonthChanged (month) {
    },
    // 选择单个日期
    handleDayChanged (day) {
    },
    delHour (val) {
      // 删除二次确认
      this.$confirm('确认删除选中的信息吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功！'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 按钮级授权
    authorization (data) {
      for (let i in data) {
        if (data['sel'] === 0) {
          this.btnSel = false;
        }
        if (data['add'] === 0) {
          this.btnAdd = false;
        }
        if (data['del'] === 0) {
          this.btnDel = false;
        }
        if (data['upload'] === 0) {
          this.btnUpload = false;
        }
        if (data['down'] === 0) {
          this.btnDown = false;
        }
        if (data['edit'] === 0) {
          this.btnEdit = false;
        }
        return i;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
